package main;

import java.util.ArrayList;
import threads.UserCleaner;

/**
 *
 * @author x3m
 */
public class OnlineUsers {
    private static OnlineUsers _instance = null;
    private static ArrayList<User> _users = null;

    public synchronized static OnlineUsers getInstance() {
        if (_instance == null) {
                _instance = new OnlineUsers();
                _users = new ArrayList<>();
                
                UserCleaner cleaner = new UserCleaner(_users);
                Thread cleaner_thread = new Thread(cleaner);
                cleaner_thread.setName("cleaner");
                cleaner_thread.start();
        }
        return _instance;
    }

    public synchronized static Boolean updateUser(User user){
        int count = 0;
        for (int i = 0; i < _users.size(); i++) {
            if (_users.get(i).getLogin().equals(user.getLogin())) {
                count++;
                break;
            }
        }
        if (count == 0) {
            _users.add(user);
            return true;
        }else{
            return false;
        }
    }
    
    public static void removeUser(User user){
        for (int i = 0; i < _users.size(); i++) {
            if (_users.get(i).getLogin().equals(user.getLogin())) {
                _users.remove(i);
            }
        }
    }
    
    public static ArrayList<User> getOnlineUsers(){
        return _users;
    }    
}
